interface Task {
    name: string;
    status: string;
    fun: Function;
    timeout: number;
}

const TaskList:Task[] = [];
const MAX_RUN_TASK = 1;
const RUNNING_TASK:Task[] = [];
let RUN_STATUS = "WAIT";


export const addTask = (taskFun:Function, name:string, timeout:number) => {
    if (timeout === null) {
        timeout = 0;
    }
    TaskList.push({
        name: `${name}`,
        status: 'WAIT',
        fun: taskFun,
        timeout: timeout
    })
}

export const startRunTask = async () => {
    // console.log(`任务开始`)
    if (TaskList.length <= 0) {
        // console.log('没有任务')
        return;
    }

    if (RUN_STATUS === "STOP") {
        // console.log("任务停止")
        return;
    }

    for (let i = RUNNING_TASK.length; i < MAX_RUN_TASK; i++) {
        RUN_STATUS = "RUNNING"
        RUNNING_TASK.push(TaskList.shift())
    }

    for (let i = 0; i < RUNNING_TASK.length; i++) {

        if (RUNNING_TASK[i].status !== "WAIT") {
            continue;
        }

        new Promise(async resolve => {
            let task = RUNNING_TASK[i]
            task.status = "RUNNING"
            await task.fun()
            task.status = "DONE"

            if (task.timeout !== 0) {
                await new Promise(resolve => {
                    setTimeout(() => {
                        resolve("timeOK")
                    }, task.timeout)
                })
            }

            removeTask()
            resolve("ok")
        }).then(res => {
            // console.log("看看还有没有任务")
            if (TaskList.length > 0 && RUNNING_TASK.length < MAX_RUN_TASK) {
                startRunTask()
            }
        })

    }

}


export const stopRunTask = () => {
    RUN_STATUS = "STOP"
}

const removeTask = () => {
    for (let i = 0;i < RUNNING_TASK.length; i++) {
        if (RUNNING_TASK[i].status === "DONE") {
            RUNNING_TASK.splice(i,1);
            return;
        }
    }
}

//测试函数
// export const testTaskList = async () => {
//     for (let i = 0; i < 10; i++) {
//         addTask(testFun, `${i}`)
//     }
//     startRunTask()
//     // await testFun("aaa")
//     // console.log("ffkd")
//     // console.log("hhh")
// }

// const testFun = async (name:string) => {
//     let time = Math.random() * 1200 + 1000
//     await new Promise(resolve => {
//         setTimeout(() => {
//             //
//             resolve("a")
//         },time)
//     })
// }


